/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.wlhy.report.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.third.jg.report.freight.information.constant.enums.AhUploadStatusEnum;
import org.jeecg.modules.third.jg.report.freight.information.constant.enums.ReportDocTypeEnum;
import org.jeecg.modules.third.jg.report.freight.information.dto.AppInfoDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.DriverDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.VehicleDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.financial.FinancialDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.shippingnote.ShippingNoteDTO;
import org.jeecg.modules.third.jg.report.freight.information.model.R;
import org.jeecg.modules.third.jg.report.freight.information.service.SxReportPlatformService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverReport;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverReportService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleReport;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleType;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleReportService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.report.IReportService;
import org.jeecg.modules.wlhy.shipping.constant.ShippingPayStatus;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @BelongsPackage: org.jeecg.modules.wlhy.report.impl
 * @Author: duanlikao
 * @CreateTime: 2023-03-08 09:24
 * @Description:
 * @Version: 1.0
 */
@Service
@Slf4j
public class SxiReportService implements IReportService {
    @Resource
    private BaseReportService baseReportService;

    @Resource
    private IHyDriverService driverService;

    @Resource
    private IHyVehicleService vehicleService;

    @Resource
    private IHyDriverReportService hyDriverReportService;

    @Resource
    private IHyVehicleReportService vehicleReportService;

    @Autowired
    private SxReportPlatformService sxReportPlatformService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Override
    public ReportPlatformEnum getReportType() {
        return ReportPlatformEnum.REPORT_PLATFORM_SX;
    }
    @Override
    public void checkReport() {
        //山西监管平台
        if (!HyCfgUtil.isUsed2("shanxi_report")) {
            throw new JeecgBootException("山西监管平台未配置参数!");
        }
    }

    @Override
    public AppInfoDTO getAppInfo() {
        return this.sxReportPlatformService.getAppInfo();
    }

    @Override
    public Result setReportInfo(HyCompanyConfig hyCompanyConfig) {

        if (StrUtil.isEmpty(hyCompanyConfig.getReportUrl())
                || StrUtil.isEmpty(hyCompanyConfig.getReportUsername())
                || StrUtil.isEmpty(hyCompanyConfig.getReportPassword())) {
            throw new JeecgBootException("山西监管平台未配置参数!");
        }

        this.sxReportPlatformService.setReportInfo(hyCompanyConfig.getReportUrl(),
                hyCompanyConfig.getReportUsername(),
                hyCompanyConfig.getReportPassword(),
                hyCompanyConfig.getReportPublickey(),
                hyCompanyConfig.getReportAppid(),
                hyCompanyConfig.getReportAppkey(),
                hyCompanyConfig.getReportAppsender(),
                hyCompanyConfig.getReportApprelease());
        return Result.ok("设置成功");
    }

    @Override
    @Deprecated
    public boolean report(HyShippingNote hyShippingNote) {
        return false;
    }

    @Override
    public Result reportShippingNote(HyShippingNote hyShippingNote) {
        Result result = checkDriverAndVehicle(hyShippingNote);
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadSxShippingNote(hyShippingNote);
    }

    @Override
    public Result reportCapitalFlow(HyShippingNote hyShippingNote) {
        Result result = checkDriverAndVehicle(hyShippingNote);
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadSxCapitalFlow(hyShippingNote.getId());
    }

    //上报运单和资金流水前，先确认司机、车辆的上传状态
    private Result checkDriverAndVehicle(HyShippingNote hyShippingNote) {

        String driverId = hyShippingNote.getDriverId();
        String vehicleId = hyShippingNote.getVehicleId();
        if (StrUtil.isEmpty(driverId)) {
            return Result.error("当前运单司机信息不存在");
        }

        if (StrUtil.isEmpty(vehicleId)) {
            return Result.error("当前运单车辆信息不存在");
        }

        //自动上报司机和车辆配置
        String autoUpload = HyCfgUtil.getCfgItem2("shanxi_report","auto_upload");
        boolean bDriverUploadStatus = this.hyDriverReportService.checkUploadStatus(driverId, hyShippingNote.getCompanyId(),
                ReportPlatformEnum.REPORT_PLATFORM_AH.getCode());
        if (!bDriverUploadStatus) {
            if (StrUtil.isEmpty(autoUpload) || !autoUpload.equals("1")) {
                return Result.error("请先同步司机数据");
            }
            log.warn("司机未上报山西监管，开始同步司机数据, {}", driverId);
            Result dResult = this.reportDriver(driverId, hyShippingNote.getCompanyId());
            if (!dResult.getCode().equals(CommonConstant.SC_OK_200)) {
                return dResult;
            }
        }

        boolean bVehicleUploadStatus = this.vehicleReportService.checkUploadStatus(vehicleId, hyShippingNote.getCompanyId(),
                ReportPlatformEnum.REPORT_PLATFORM_AH.getCode());
        if (!bVehicleUploadStatus) {
            if (StrUtil.isEmpty(autoUpload) || !autoUpload.equals("1")) {
                return Result.error("请先同步车辆数据");
            }
            log.warn("车辆未上报山西监管，开始同步车辆数据, {}", vehicleId);
            Result vResult = this.reportVehicle(vehicleId, hyShippingNote.getCompanyId());
            if (!vResult.getCode().equals(CommonConstant.SC_OK_200)) {
                return vResult;
            }
        }

        return Result.OK();
    }


    public Result uploadSxCapitalFlow(String shippingId){

        HyShippingNote hyShippingNote = hyShippingNoteService.getById(shippingId);
        if (!hyShippingNote.getUploadStatus().equals("1")) {
            return Result.error("请先上传运单数据");
        }

        if (!hyShippingNote.getShippingPayStatus().equals(ShippingPayStatus.支付完成.getValue())) {
            return Result.error("该运单未支付完成");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("shipping_id", shippingId);
        List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(queryWrapper);

        if (CollectionUtils.isEmpty(shippingNoteBills)) {
            throw new JeecgBootException("未找到对应数据");
        }

        FinancialDTO financialDTO = baseReportService.getFinancialDTO(shippingNoteBills,hyShippingNote);
        String jsonString = JSONObject.toJSONString(financialDTO);

        String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_ZJ.getCode();
        ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);
        try{
            String reportResult = sxReportPlatformService.sendReport(reportDocTypeEnum,jsonString);
            if(StringUtils.isNotEmpty(reportResult)){
                R result = JSON.parseObject(reportResult, R.class);
                boolean res =  result.getCode() == 1001 ?  true : false;
                for(HyShippingNoteBill shippingNoteBillDb: shippingNoteBills) {
                    shippingNoteBillDb.setUploadStatus(res ?  "1" : "2");
                    shippingNoteBillDb.setUploadDate(new Date());
                    shippingNoteBillDb.setReportFailureReason(res ?  "" : result.getMessage()+result.getData());
                    shippingNoteBillDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
                }
                hyShippingNoteBillService.updateBatchById(shippingNoteBills);
                return res ? Result.OK("上报成功"): Result.error(result.getMessage());
            }
        }catch (Exception e){
            for(HyShippingNoteBill shippingNoteBillDb: shippingNoteBills){
                shippingNoteBillDb.setUploadStatus( "2");
                shippingNoteBillDb.setUploadDate(new Date());
                shippingNoteBillDb.setReportFailureReason(e.getMessage());
                shippingNoteBillDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
            }
            hyShippingNoteBillService.updateBatchById(shippingNoteBills);
        }
        return Result.error("资金流水数据上报错误");
    }


    public Result uploadSxShippingNote(HyShippingNote hyShippingNote) {
        HyShippingNote ShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (ShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }

        HyVehicle hyVehicle = this.vehicleService.getById(ShippingNoteDb.getVehicleId());
        if (ShippingNoteDb.getGoodsWeightLoading().compareTo(hyVehicle.getVehicleTonnage()) > 0 ){
            ShippingNoteDb.setUploadStatus("2");
            ShippingNoteDb.setUploadDate(new Date());
            ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
            ShippingNoteDb.setReportFailureReason("货物质量超过车辆核定载质量货物质量:"+ShippingNoteDb.getGoodsWeightLoading()+"车辆核定载质量:"+hyVehicle.getVehicleTonnage());
            this.hyShippingNoteService.updateById(ShippingNoteDb);
            log.error("山西监管上报超载 货物重量 {} > 核定载质量 {}", ShippingNoteDb.getGoodsWeightLoading(), hyVehicle.getVehicleTonnage());
            return Result.error("货物重量超过车辆核定载质量, 货物重量:" + ShippingNoteDb.getGoodsWeightLoading() + " ,车辆核定载质量:" + hyVehicle.getVehicleTonnage());
        }

        try {
//            if(!"2".equals(hyShippingNote.getUploadStatus())) {
//                baseReportService.checkShippingNoteRoute(hyShippingNote);
//            }

            ShippingNoteDTO shippingNoteDTO = baseReportService.shippingNoteTOShippingNoteDTO(ShippingNoteDb, hyShippingNote.getCompanyId());
            String jsonString = JSONObject.toJSONString(shippingNoteDTO);
            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_YD.getCode();
            ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);

            String reportResult = sxReportPlatformService.sendReport(reportDocTypeEnum, jsonString);
            if (StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean res = result.getCode() == 1001  ? true : false;
                ShippingNoteDb.setUploadStatus(res ? "1" : "2");
                ShippingNoteDb.setUploadDate(new Date());
                ShippingNoteDb.setReportFailureReason(res ? "" : result.getMessage()+result.getData());
                ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
                hyShippingNoteService.updateById(ShippingNoteDb);
                return res ? Result.OK("上报成功"): Result.error(result.getMessage());
            }
        } catch (Exception e) {
            ShippingNoteDb.setUploadStatus("2");
            ShippingNoteDb.setUploadDate(new Date());
            ShippingNoteDb.setReportFailureReason(e.getMessage());
            ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
            hyShippingNoteService.updateById(ShippingNoteDb);
        }

        return Result.error("运单数据上报错误");
    }

    /**
     * 平台司机上报
     *
     * @param driverId
     * @return
     */
    @Override
    public Result reportDriver(String driverId, String companyId) {
        HyDriver hyDriverDb = driverService.getById(driverId);
        if (hyDriverDb == null) {
            throw new JeecgBootException("未找到该司机数据");
        }
        //if (hyDriverReportService.checkUploadStatus(driverId ,ReportPlatformEnum.REPORT_PLATFORM_HB.getCode())) {
        //    throw new JeecgBootException("该司机已经上传过，请勿重复上传");
        //}
        HyDriverReport hyDriverReport = new HyDriverReport();
        try {
            //人员从业资格证验证
            if(!driverService.checkQualificationV2(hyDriverDb)){
                throw new JeecgBootException("人员从业资格证验证号不正确或者已过期，请修改后重新上传！");
            }

            DriverDTO driverDTO = baseReportService.hyDriverTODriverDTO(hyDriverDb);
            String jsonString = JSONObject.toJSONString(driverDTO);

            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_JSY.getCode();
            ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);

            String reportResult = sxReportPlatformService.sendReport(reportDocTypeEnum, jsonString);
            if (StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean res = (result.getCode() == 1001) ? true : false;
                hyDriverReport.setCompanyId(companyId);
                hyDriverReport.setDriverId(driverId);
                hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
                hyDriverReport.setDriverUploadStatus(res ? "1" : "2");
                hyDriverReport.setUploadDate( new Date() );
                hyDriverReport.setDriverReportFailureReason(result.getMsg()+result.getData() );
                hyDriverReportService.saveDriverReport(hyDriverReport);

                this.driverService.updateSxUploadStatusById(driverId, hyDriverReport.getDriverUploadStatus());
                log.info("山西监管更新司机上报回执信息, {}, {}", res, result.getMsg());

                return res ? Result.OK("上报成功") : Result.error(result.getMsg());
            } else {
                throw new JeecgBootException("未知异常");
            }
        }catch (Exception e){
            hyDriverReport.setId(driverId);
            hyDriverReport.setDriverId(driverId);
            hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
            hyDriverReport.setDriverUploadStatus( "2");
            hyDriverReport.setUploadDate( new Date() );
            hyDriverReport.setDriverReportFailureReason(e.getMessage());
            hyDriverReportService.saveDriverReport(hyDriverReport);
        }

        return Result.error("上报司机数据错误");
    }

    @Override
    public Result reportVehicle(String vehicleId, String companyId) {
        HyVehicle hyVehiclDb = vehicleService.getById(vehicleId);
        if(hyVehiclDb == null) {
            throw new JeecgBootException("未找到该车辆数据");
        }

        HyVehicleReport hyVehicleReport = new HyVehicleReport();
        if (StringUtils.isEmpty(hyVehiclDb.getRoadTransportNumber())) {
            throw new JeecgBootException("车辆道路运输证不能为空");
        }

        if (!vehicleService.checkRTCNoV2(hyVehiclDb)) {
            throw new JeecgBootException("车辆道路运输证号不正确或者已过期，请修改后重新上传");
        }

        List<HyVehicleType> hyVehicleTypeList = vehicleService.getHyVehicleByPid("1");
        HyVehicleType hyVehicleType = hyVehicleTypeList.stream().filter(s->hyVehiclDb.getVehicleType().contains(s.getText())).findAny().orElse(null);
        if (hyVehicleType == null) {
            throw new JeecgBootException("车辆类型不存在,请修改后重新上报");
        }

//        HyVehicleType hyVehicleType = vehicleService.getHyVehicleType(hyVehiclDb.getVehicleType());
//        if (hyVehicleType == null) {
//            throw new JeecgBootException("车辆类型不存在,修改后请重新上报");
//        }

        //载重量上限判断
        if (hyVehiclDb.getVehicleTonnage().intValue() > 90 ||
                hyVehiclDb.getVehicleTonnage().compareTo(hyVehiclDb.getGrossMass()) > -1) {
            throw new JeecgBootException("车辆的核载质量不在有效范围内");
        }

        //吨位上限判断
        if (hyVehiclDb.getGrossMass().intValue() > 90) {
            throw new JeecgBootException("车辆的总质量不在有效范围内");
        }

        hyVehiclDb.setVehicleType(hyVehicleType.getValue());
        VehicleDTO vehicleDTO = baseReportService.hyVehicleDTOTOVehicleDTO(hyVehiclDb);

        if (hyVehicleType.getText().contains("挂")) {
            //先上传挂车车辆信息
            Result r = this.uploadTrailerVehicle(hyVehiclDb);
            if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                return r;
            }

            vehicleDTO.setTrailerVehiclePlateNumber(hyVehiclDb.getTrailerVehiclePlateNumber());
        }

        try {
            String jsonString = JSONObject.toJSONString(vehicleDTO);

            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_CL.getCode();
            ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);

            String reportResult = sxReportPlatformService.sendReport(reportDocTypeEnum,jsonString);
            if(StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean res =  (result.getCode() == 1001) ?  true : false;
                hyVehicleReport.setCompanyId(companyId);
                hyVehicleReport.setVehicleId(vehicleId);
                hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
                hyVehicleReport.setVehicleUploadStatus(res ? "1" : "2");
                hyVehicleReport.setUploadDate( new Date() );
                hyVehicleReport.setVehicleReportFailureReason(result.getMsg()+result.getData());
                vehicleReportService.saveVehicleReport(hyVehicleReport);

                this.vehicleService.updateSxUploadStatusById(vehicleId, hyVehicleReport.getVehicleUploadStatus());
                log.info("山西监管更新车辆上报回执信息, {}, {}", res, result.getMsg());

                return res ? Result.OK("上报成功") : Result.error(result.getMsg());
            } else {
                throw new JeecgBootException("未知异常");
            }
        } catch (Exception e) {
            hyVehicleReport.setId(vehicleId);
            hyVehicleReport.setVehicleId(vehicleId);
            hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SX.getCode());
            hyVehicleReport.setVehicleUploadStatus( "2");
            hyVehicleReport.setUploadDate( new Date() );
            hyVehicleReport.setVehicleReportFailureReason(e.getMessage());
            vehicleReportService.saveVehicleReport(hyVehicleReport);
        }

        return Result.error("上报车辆数据错误");
    }


    //上传挂车车辆信息
    public Result uploadTrailerVehicle(HyVehicle hyVehiclDb) {

        if (StringUtils.isBlank(hyVehiclDb.getTrailerVehiclePlateNumber())) {
            throw new JeecgBootException("挂车车牌号不能为空");
        }

        if (!hyVehiclDb.getTrailerVehiclePlateNumber().endsWith("挂") && !hyVehiclDb.getTrailerVehiclePlateNumber().endsWith("超")) {
            throw new JeecgBootException("挂车车牌号不正确");
        }

//        if (StrUtil.isEmpty(hyVehiclDb.getTrailerVehicleRoadTransportNumber())) {
//            throw new JeecgBootException("挂车道路运输证号不存在");
//        }

//        if (StrUtil.isEmpty(hyVehiclDb.getTrailerVehicleType())) {
//            throw new JeecgBootException("挂车车辆类型不存在");
//        }

        VehicleDTO trailerDto = this.baseReportService.hyVehicleToTrailerVehicleDTO(hyVehiclDb);
        String jsonString = JSONObject.toJSONString(trailerDto);

        String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_CL.getCode();
        ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);

        try {
            String reportResult = sxReportPlatformService.sendReport(reportDocTypeEnum,jsonString);
            if (StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean res =  (result.getCode() == 1001) ?  true : false;
                log.info("山西监管挂车上报回执信息, {}, {}", res, result.getMsg());
                return res ? Result.OK("上报成功") : Result.error(result.getMsg());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

        return Result.error("挂车信息上报出现错误");
    }

}
